import plugin from '../../lib/plugins/plugin.js';
import fetch from "node-fetch";
import NoteUser from "../genshin/model/mys/NoteUser.js";
import puppeteer from 'puppeteer';
import fs from 'fs';

export class honkai extends plugin {
  constructor() {
    super({
      name: '手账',
      dsc: '崩坏3水晶手账',
      event: 'message',
      priority: 1,
      rule: [
        {
          reg: "^#?(bhs|水晶手账|手账)$",
          fnc: 'honkai'
        }
      ]
    });
  }

  async user() {
    return await NoteUser.create(this.e);
  }

async generateHTML(e, nickname, res) {
    return `
        <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${nickname}的崩坏3手账</title>

  <style>
    :root {
      --custom-colors: #00FF00, #00BFFF, #9400D3, #FFD700, #FF4500;
      --bg-url: url('https://s21.ax1x.com/2024/04/13/pFjRzVO.png');
    }

    body {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-image: var(--bg-url);
      background-position: center center;
      background-size: cover;
      color: transparent;
    }

    .container {
      text-align: center;
      font-weight: bold;
      backdrop-filter: blur(10px);
      padding: 6rem;
      box-shadow: 0 ¼rem ⅔rem rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .avatar-container {
      position: relative;
      margin-bottom: 2rem;
    }

    .avatar {
      width: .jpg; /* 调整头像大小，根据实际需求设置 */
      height: auto;
      border-radius: 50%; /* 添加圆形边框 */
      box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.2); /* 添加头像阴影 */
    }

    h1,
    p {
      background-image: linear-gradient(to right, var(--custom-colors));
      -webkit-background-clip: text;
      color: transparent;
      font-size: clamp(1.˜rem, 3vw, 2.5rem); /* 使用clamp实现文字大小自适应 */
      letter-spacing: 0.1em;
      text-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.2);
      animation: gradient-shift ¾s ease-in-out infinite alternate;
    }

    @keyframes gradient-shift {
      0% {
        background-position: 0 0;
      }
      100% {
        background-position: 100% 0;
      }
    }

    img.logo {
      width: 7vw;
      height: auto;
      image-rendering: pixelated;
    }

    img {
      max-width: 100%;
      height: auto;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="avatar-container">
      <!-- 用户头像展示 -->
      <img src="${imgUrls[0]}" alt="User Avatar" class="avatar">
    </div>
    <img src="https://s21.ax1x.com/2024/04/13/pFjWFxI.png" alt="logo" class="logo">
    <h1>${nickname}舰长的${res.data.month}月手账</h1>
    <p>UID：${res.data.uid}</p>
    <p>截止到 ${res.data.date}</p>
    <p>本月已获得水晶：${res.data.month_hcoin}</p>
    <p>本月已获得星石：${res.data.month_star}</p>
    <p>今日已获得水晶：${res.data.day_hcoin}</p>
    <p>今日已获得星石：${res.data.day_star}</p>
    <p>昨日已获得水晶：${res.data.last_hcoin}</p>
    <p>昨日已获得星石：${res.data.last_star}</p>
    <p>数据存在1小时左右的延迟</p>
  </div>
</body>

</html>
    `;
}
  async honkai(e) {
    let user = await this.user();
    if (!user.hasCk) {
      this.e.reply('当前尚未绑定cookie');
      return;
    }
    let mys = user.getMysUser(this.e);
    let ck = mys.ck;

    const myHeaders = new Headers();
    myHeaders.append("Cookie", ck);
    myHeaders.append("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67");

    const requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };

    let url = 'https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie';

    fetch(url, requestOptions)
      .then(response => response.text())
      .then(data => {
        var info = JSON.parse(data);
        if (info.retcode == 0) {
          var bind_uid = info.data.list[0].game_uid;
          var bind_region = info.data.list[0].region;
          var nickname = info.data.list[0].nickname;
          let urls = `https://api.mihoyo.com/bh3-weekly_finance/api/index?game_biz=bh3_cn&bind_uid=${bind_uid}&bind_region=${bind_region}`;

          fetch(urls, requestOptions)
            .then(response => response.text())
            .then(async data => {
              var res = JSON.parse(data);
              if (res.retcode == 0) {
                const htmlContent = await this.generateHTML(e, nickname, res);

                // Create directory if not exists
                const directory = 'resources/bh3';
                if (!fs.existsSync(directory)) {
                  fs.mkdirSync(directory, { recursive: true });
                }

                // Launch Puppeteer and take screenshot
                const browser = await puppeteer.launch({
                  executablePath: '/usr/bin/chromium-browser', // 替换为你的 Chrome 可执行文件路径
                  args: ['--no-sandbox']
                });
                const page = await browser.newPage();
                await page.setContent(htmlContent);
                await page.screenshot({ path: 'resources/bh3/honkai_handbook.png' });

                // Reply with the screenshot
                e.reply('请稍候，正在生成崩坏3手账截图...');
                await e.reply([
                  segment.image("resources/bh3/honkai_handbook.png"),
                ]);

                await browser.close();
              } else {
                e.reply(res.message);
              }
            });
        } else {
          e.reply(info.message);
        }
      });
  }
}
